package util

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"net/smtp"
	"ops.alert.center.service/internal/model"
	"strconv"
	"time"
)

var (
	D *gomail.Dialer
)

type UnencryptedAuth struct {
	smtp.Auth
}

func InitEmailConnect() {
	D = gomail.NewDialer("mail.gangtiequn.com", 25, "monitor@gangtiequn.com", "399GCG")
	D.Auth = UnencryptedAuth{
		smtp.PlainAuth(
			"",
			"monitor@gangtiequn.com",
			"399GCG",
			"mail.gangtiequn.com",
		),
	}
}

func SendMail(subject string, content string, mails []string) error {
	InitEmailConnect()
	M := gomail.NewMessage()
	M.SetHeader("From", "Alert Center <monitor@gangtiequn.com>")
	M.SetHeader("To", mails...)
	M.SetHeader("Subject", subject)
	M.SetBody("text/html", content)
	if err := D.DialAndSend(M); err != nil {
		return err
	}
	return nil
}

func (a UnencryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
	s := *server
	s.TLS = true
	return a.Auth.Start(&s)
}

func SendEmails(ThisEvent model.AlertEvent, Emails []string) {
	//发送企业微信测试
	var Time string
	Time = time.Unix(1644837126000/1000, 0).Format("2006-01-02 15:04:05")
	email_template, _ := Pingjietemplate(strconv.Itoa(ThisEvent.Status),
		ThisEvent.SystemAlias,
		ThisEvent.Env, ThisEvent.AlertContent, ThisEvent.EventDatasource,
		ThisEvent.EventOccurIp,
		ThisEvent.EventDatasourceName,
		ThisEvent.EventCategory, Time, 1, 0)
	Subject := fmt.Sprintf("告警中心 %s 环境 %s 告警", ThisEvent.Env, ThisEvent.SystemAlias)
	err2 := SendMail(Subject, email_template, Emails)
	if err2 != nil {
		fmt.Println("发送微信失败!")
		fmt.Println(err2)
	}
}
